<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\Business;
use app\common\model\ProductCate;
use app\common\model\UserCollectBusiness;
use app\common\tool\Result;
use think\facade\Event;
use think\Response;

class BusinessMall extends Base
{

    /**
     * @param $id
     * @return Response
     * 原点 2022年12月30日15:40:01 店铺信息
     */
    public function index($id): Response
    {
        try {
            $this->verifyToken();
            $business = Business::where(['id' => $id, 'is_del' => 0, 'status' => 1])
                ->field('id,title,logo,cover,customer_tel,fans')->find();
            if (empty($business)) {
                return Result::fail('店铺已关门');
            }
            //是否关注店铺
            $business->is_fans = $this->user ? UserCollectBusiness::isCollect($this->user->id, $id) : 0;
            if ($this->user) Event::trigger('BusinessView', ['uid' => $this->user->id, 'business_id' => $business->id]);
            return Result::success('success', $business);
        } catch (\Exception $e) {
            return Result::fail('服务器错误，请稍后再试');
        }
    }

    /**
     * @return Response
     * 原点 2022年12月30日15:07:50 关注/取消关注店铺
     */
    public function collect(): Response
    {
        try {
            $param = $this->request->post();
            return Result::fastReturn(
                $param['type'] == 1 ?
                    UserCollectBusiness::add($this->user->id, $param['id']) :
                    UserCollectBusiness::cancel($param['id'], $this->user->id));
        } catch (\Exception $e) {
            return Result::fail('服务器错误，请稍后再试');
        }
    }

    /**
     * @param $pid - 父级ID，默认0
     * @return Response
     * 原点 2022年12月24日09:32:20 获取商家允许的经营类目，一级分类
     */
    public function getCate($business_id): Response
    {
        $data = ProductCate::whereIn('id', $business_id)
            ->where(['is_del' => 0, 'status' => 1, 'pid' => 0])->field('id,title')->select();
        return Result::success('success', $data);
    }


}

